var express = require('express');
var router = express.Router();
var config = require('../lib/config/config').config;
var http = require('http');

//for proxy part
router.post('*',function(req, res, next){
    var data =  JSON.stringify(req.body);

    var opt = {
        host:config.kubernetes.host,
        port:config.kubernetes.port,
        method: 'POST',
        path: req.url,
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': data.length
        }
    };

    var req_post =http.request(opt,function(response){
        var postData = "";
        response.addListener("data", function (postDataChunk) {
            postData += postDataChunk;
        });
        response.addListener("end", function () {
            res.send(postData);
        });
    });

    req_post.write(data);
    req_post.end();
});

router.put('*',function(req, res, next){
    var data =  JSON.stringify(req.body);

    var opt = {
        host:config.kubernetes.host,
        port:config.kubernetes.port,
        method: 'PUT',
        path: req.url,
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': data.length
        }
    };

    var req_post =http.request(opt,function(response){
        var postData = "";
        response.addListener("data", function (postDataChunk) {
            postData += postDataChunk;
        });
        response.addListener("end", function () {
            res.send(postData);
        });
    });

    req_post.write(data);
    req_post.end();
});

router.get('*', function(req, res, next) {

    var url = "http://"+config.kubernetes.host+":"+config.kubernetes.port + req.url;
    http.get(url,function(response){
        var postData = "";
        response.addListener("data", function (postDataChunk) {
            postData += postDataChunk;
        });
        response.addListener("end", function () {
            res.send(postData);
        });
    });
});

router.delete('*',function(req, res, next){

    var opt = {
        host:config.kubernetes.host,
        port:config.kubernetes.port,
        method: 'DELETE',
        path: req.url
    };

    var req_post =http.request(opt,function(response){
        var postData = "";
        response.addListener("data", function (postDataChunk) {
            postData += postDataChunk;
        });
        response.addListener("end", function () {
            res.send(postData);
        });
    });
    req_post.end();
});

module.exports = router;